package org.algorithm.二师兄.链表;

import org.algorithm.common.ListNode;

/****
 *  1 -> 2 -> 3
 *  0 -> 1 -> 1
 *  结果： 4 -> 3 -> 1
 */
public class 链表相加 {

    public static void main(String[] args) {
        ListNode listNode = ListNode.build(1,2,3);
        ListNode listNode1 = ListNode.build(7,6,5,4);

        ListNode listNode2 = addListNode(listNode, listNode1);
        ListNode.print(listNode2);

    }

    private static ListNode addListNode(ListNode left, ListNode right) {
        if (left == null && right != null) return right;
        if (right == null && left != null) return left;

        int ants = 0;
        ListNode dummy = new ListNode(-1);
        ListNode curr = dummy;

        while (left != null && right != null) {
            int sum = left.val + right.val + ants;
            ants = sum / 10;
            curr.next = new ListNode(sum%10);
            left = left.next;
            right = right.next;
            curr = curr.next;
        }

        while (left != null) {
            int sum = left.val + ants;
            ants = sum/10;
            curr.next = new ListNode(sum%10);
            left = left.next;
            curr = curr.next;
        }

        while (right != null) {
            int sum = right.val + ants;
            ants = sum/10;
            curr.next = new ListNode(sum%10);
            right = right.next;
            curr = curr.next;
        }

        if (ants > 0) {
            curr.next = new ListNode(ants);
        }
        return dummy.next;
    }
}
